<template>
  <div class="login-wrap">
    <div class="login-div" v-show='!C1'>
      <!--左边透明-->
      <div class="left_transparent">
        <div style="width:100%;padding-left:15px;">
          <div style="display:flex;align-items:center;">
            <span style="color:#fff;font-size:22px;">欢迎来到</span>
            <img src="../../static/images/jiantou.png" class="left_icon" />
          </div>
          <div class="left_div_white"></div>
          <div>
            <span style="color:#fff;font-size:22px;">监理眼后台管理系统</span>
          </div>
        </div>
      </div>
      <!--右边登录 class="login-form"-->
      <div id="loginIcon">
        <el-form id="login_input" class="login-form" :rules="loginRules" ref="formName" :model="form">
          <el-form-item>
            <el-input
              autocomplete="on"
              v-model="form.ueserName"
              clearable
              placeholder="账号"
              style="width:100%"
            >
              <template slot="prepend">
                <img src="../../static/images/loginPic.png" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              clearable
              autocomplete="off"
              v-model="form.password"
              show-password
              placeholder="密码"
              style="width:100%"
            >
              <template slot="prepend">
                <img src="../../static/images/password.png" />
              </template>
            </el-input>
          </el-form-item>
          <!--滑动验证-->
          <el-form-item>
            <div class="form-inline-input">
              <div class="code-box" id="code-box">
                <el-input type="text" name="code" class="code-input"> </el-input>
                <h4>请向右滑动验证</h4>
                <p></p>
                <!-- <span>>>></span> -->
                <span>
                  <img src="../../static/images/arrows.gif" style="width:26px;height:26px;"/>
                </span>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="renmber_pass">
              <div>
                <el-checkbox v-model="form.checked">记住密码</el-checkbox>
              </div>
              <div>
                <span class="forget_pass" @click="forget()">忘记密码?</span>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="login_button">
              <el-button type="primary" style="width:100%;background:#367FA8" @click="login('form')">登录</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <myForget v-if='C1'></myForget>
  </div>
</template>
<script type="text/javascript">
import myhttp, {
  isEmpty,
  msgError,
  msgSuccess,
  msgWarning
} from "../utils/myhttp";
import api from "../utils/api";
import qs from "qs";
import { formatDate } from "../utils/date.js";
import sidentify from "./sidentify";
import validate from "../utils/validate.js";
import myForget from './forget';
export default {
  name: "login",
  global: false,
  components: { sidentify, myForget },
  data() {
    return {
      C1: false,
      form: {
        ueserName: "",
        password: "",
        code: "",
        checked: false //记住密码
      },
      identifyCodes: "1234567890abcdefghijkmnopqrstuvwxyz",
      identifyCode: "",
      isDebugLogin: false,
      loginRules: {
        // code: [
        //   { required: true, message: "请输入验证码", trigger: "blur" },
        //   { validator: validateCode, trigger: "blur" }
        // ]
      },
      ruleForm:{
        verification:false,
      },
      solider_state:0,//滑块状态 自定义
    };
  },
  watch: {
    isDebugLogin(v) {
      if (v) {
        this.refreshCode()
      }
    },
    identifyCode(v) {
      this.isDebugLogin && (this.form.code = v)
    },
  },
  created() {
    this.$route.path === "/login" && this.$root.exit(true);
    this.refreshCode();
    window.onhashchange = e=>{
        location.hash !== '#/login' && ( location.hash = '#/login' );
    };
  },
  destroyed() {
    window.onhashchange = null;
  },
  mounted() {
    //页面加载调用获取cookie值
    this.getCookie();
    //滑动验证
    var _this = this;
    //code是后台传入的验证字符串
    var code = "123456",
    codeFn = new _this.moveCode(code,_this);
  },
  methods: {
    //==============================滑动验证=================================
    //获取元素距离页面边缘的距离
    getOffset(box,direction){
      var setDirection =  (direction == 'top') ? 'offsetTop' : 'offsetLeft' ;
      var offset =  box[setDirection];
      var parentBox = box.offsetParent;
      while(parentBox){
        offset+=parentBox[setDirection];
        parentBox = parentBox.offsetParent;
      }
      parentBox = null;
      return parseInt(offset);
    },
    moveCode(code,_this){
      var fn = {codeVluae : code};
      var box = document.querySelector("#code-box"),
        progress = box.querySelector("p"),
        codeInput = box.querySelector('.code-input'),
        evenBox = box.querySelector("span");
      //默认事件
      var boxEven = ['mousedown','mousemove','mouseup'];
      //改变手机端与pc事件类型
      if(typeof document.ontouchstart == 'object'){
        boxEven = ['touchstart','touchmove','touchend'];
      }
      var goX,offsetLeft,deviation,evenWidth,endX;
      function moveFn(e){
        e.preventDefault();
        e = (boxEven['0'] == 'touchstart') ? e.touches[0] : e || window.event;
        endX = e.clientX - goX;
        endX = (endX > 0) ? (endX > evenWidth) ? evenWidth : endX : 0;
        if(endX > evenWidth * 0.7){
          progress.innerText = '松开验证';
          progress.style.backgroundColor = "#66CC66";
        }else{
          progress.innerText = '';
          progress.style.backgroundColor = "#E0FE9A";
        }
        progress.style.width = endX+deviation+'px';
        evenBox.style.left = endX+'px';
      }
      const self = this;
      function removeFn() {
        document.removeEventListener(boxEven['2'],removeFn,false);
        document.removeEventListener(boxEven['1'],moveFn,false);
        if(endX > evenWidth * 0.7){
          progress.innerText = '验证成功';
          progress.style.width = evenWidth+deviation+'px';
          evenBox.style.left = evenWidth+'px'
          codeInput.value = fn.codeVluae;
          evenBox.onmousedown = null;
          _this.ruleForm.verification = true;
          _this.solider_state = 1;
        }else{
          progress.style.width = '0px';
          evenBox.style.left = '0px';
          _this.solider_state = 0;
        }
      };
      function getOffset(box,direction){
        var setDirection =  (direction == 'top') ? 'offsetTop' : 'offsetLeft' ;
        var offset =  box[setDirection];
        var parentBox = box.offsetParent;
        while(parentBox){
          offset+=parentBox[setDirection];
          parentBox = parentBox.offsetParent;
        }
        parentBox = null;
        return parseInt(offset);
      };
      evenBox.addEventListener(boxEven['0'], function(e) {
        e = (boxEven['0'] == 'touchstart') ? e.touches[0] : e || window.event;
          goX = e.clientX,
            offsetLeft = getOffset(box,'left'),
            deviation = this.clientWidth,
            evenWidth = box.clientWidth - deviation,
            endX;
        document.addEventListener(boxEven['1'],moveFn,false);
        document.addEventListener(boxEven['2'],removeFn,false);
      },false);
      fn.setCode = function(code){
        if(code)
          fn.codeVluae = code;
      }
      fn.getCode = function(){
        return fn.codeVluae;
      }
      fn.resetCode = function(){
        evenBox.removeAttribute('style');
        progress.removeAttribute('style');
        codeInput.value = '';
      };
      return fn;
    },
    //==========================================================================
    //忘记密码
    forget(){
      this.C1 = true;
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length)
        ];
      }
    },
    login() {
      if (isEmpty(this.form.ueserName)) {
        msgWarning(this, "请输入用户名！");
      } else if (isEmpty(this.form.password)) {
        msgWarning(this, "请输入密码！");
      } else if (this.solider_state != 1){
        msgWarning(this, "请滑动上方进行验证！");
      }else {
        this.doLogin();
      }
    },
    openLoading() {
      this.loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    doLogin: async function() {
      this.openLoading();
      //修改回车验证问题
      // if (this.form.code !== this.identifyCode) {
      //  $.msgError('请填写正确验证码');
      //  this.loading.close();
      //  this.refreshCode();
      //  return
      // }
      this.$refs.formName.validate((valid) => {
        if (valid) {
          const self = this;
          //判断复选框是否被勾选 勾选则调用配置cookie方法
          if (self.form.checked == true) {
            //传入账号名，密码，和保存天数3个参数
            self.setCookie(self.form.ueserName, self.form.password, 7);
          }else {
            self.clearCookie();
            return false;
            //清空Cookie
          }
        } else {
          return false;
        }
      });

      var res = await $.post("login", {
        phoneNumber: this.form.ueserName,
        userPassword: this.form.password
      });
      this.loading.close();
      if (!res.success) return $.msgError(res.msg || "error!");
      res = res.user;
      localStorage.setItem("userId", res.userId);
      localStorage.setItem("roleId", res.roleId);
      localStorage.setItem("loginName", res.userName);
      localStorage.setItem("loginAccount", res.phoneNumber);
      localStorage.setItem("MyPictureID", res.userPassword);
      this.$root.isLogined = true;
      this.$router.push({name: "switchManagement"});
      /*switch (res.roleId) {
        case "1":
          //userManagement
          this.$router.push({name: "userManagement"});
          break;
        case "2":
          this.$router.push({name: "projectManagement2"});
          break;
        case "3":
          this.$router.push({name: "projectManagement3"});
          break;
      }*/
    },
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie = "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
    //读取cookie
    getCookie: function() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split('; ');
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split('='); //再次切割
          //判断查找相对应的值
          if (arr2[0] == 'userName') {
            this.form.ueserName = arr2[1];
          } else if (arr2[0] == 'userPwd') {
            this.form.password = arr2[1];
          }
        }
        this.form.checked = true;
      }
    },
    //清除cookie
    clearCookie: function() {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天
    }

  },
};
</script>

<style lang="scss" scoped>
@import "../assets/css/_lib-mixin";
html,
body {
  overflow: hidden;
}
.login-wrap {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
  box-sizing: border-box;
  background-position: center;
  background-repeat: no-repeat;
  background-image: url(../../static/images/background.png);
  background-size: cover;
}
.login-div {
  width:768px;
  display: flex;
  position: absolute;
  top: 50%;
  left: 20%;
  transform: translateY(-50%);
}
/*左边透明*/
.left_transparent {
  background: rgba(0, 0, 0, 0.4);
  padding: 50px 15px 20px 15px;
  display: flex;
  align-items: center;
  width:410px;
}
/*左侧 图标*/
.left_icon {
  width: 24px;
  height: 24px;
  margin-left: 10px;
}
/*左侧 白色透明 div*/
.left_div_white {
  background: rgba(255, 255, 255, 0.4);
  border-radius: 2px;
  height: 2px;
  width: 100%;
  margin: 10px 0;
}
/*右侧*/
#loginIcon {
  background: #fff;
  width:357px;
  height:300px;
  padding: 50px 18px 20px 18px;
}
.login-form {
  .login-code {
    cursor: pointer;
    .login-code-img {
      width: 100px;
      height: 38px;
      background-color: #eee;
      border: 1px solid #f0f0f0;
      color: #333;
      font-size: 18px;
      font-weight: bold;
      letter-spacing: 2px;
      text-indent: 2px;
      text-align: center;
    }
  }
}
/*记住密码一栏*/
.renmber_pass{
  display:flex;
  justify-content:space-between;
  height:30px;
  align-items:center;
}
.forget_pass{
  cursor:pointer;
  color: #606266;
}
.forget_pass:hover{
  color:#409eff;
}
/*滑动验证*/
.form-inline-input{
  border:1px solid #dddddd;
  border-radius:5px;
  // text-shadow: 1px 1px 1px black;
}
.form-inline-input input,
.code-box{
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 3px;
  height: 40px;
  // text-shadow: 1px 1px 1px black;
  background: #dddddd;
  border: 0;
  border-radius: 5px;
  outline: none;
}
.code-box{
  position: relative;
}
.code-box p{
  display:block;
  position: absolute;
  left: 0;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 5px;
  padding:0;
  margin:0;
}
.code-box h4{
  color:#6C6C6C;
  font-weight: normal;
}
.code-box span{
  position: absolute;
  left: 0;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 5px;
  padding:0;
  margin:0;
  width: 56px;
  background-color:#fff;
  font-size: 16px;
  cursor: pointer;
  margin-right:1px;
  color:#D6D6D6;
  display: flex;
  align-items: center;
  justify-content: center;
}
.code-box p{
  color:#fff;
  width: 0;
  background-color: #FFFF99;
  overflow: hidden;
  text-indent: -20px;
  transition: background 1s ease-in;
}
.code-box .code-input{
  display: none;
}
.code-box .code-input{
  display: none;
}
</style>
